import DialogVue from "./dialog.vue";
import { Popup } from "../popup";
import { DialogOptions, PopupComponentEvent } from "./type";
import { VNode } from "vue";
import { BasicFormBox } from "../../basic-form-box";
import { ButtonGroup } from "../../button-group";
import { BasicFormOptions } from "../../basic-form-box/type";
import { repaintProxy } from "../../utils";
import { FORM_BOX_METHOD } from "../../config";
interface DialogFormOptions {
	/** 是否打开弹出层进行表单重置，默认重置 */
	isReset?: boolean;
	/** 是否清空表单 默认不清空 */
	isClear?: boolean;
	type?: BasicFormOptions<any>["type"];
	labelWidth?: BasicFormOptions<any>["labelWidth"];
}

const baseConfig = {
	isReset: true,
	labelWidth: "",
	isClear: false,
};

export class Dialog extends Popup<DialogOptions> {
	private formInstance!: BasicFormBox;
	private buttonGroup!: ButtonGroup;
	constructor() {
		super(DialogVue);
	}
	/**
	 * 初始化表单
	 * @param callback 表单初始化的回调
	 * @param isReset 是否唤起表单时进行表单重置，默认重置
	 * @returns
	 */
	initForm<Form = Record<string, any>>(
		callback: (form: BasicFormBox<Form>, others?: { btn: ButtonGroup }) => void,
		config: DialogFormOptions = baseConfig
	): Dialog {
		this.formInstance = new BasicFormBox({
			...{
				type: "edit",
				layout: "vertical",
				options: [],
			},
			...config,
		});

		this.buttonGroup = new ButtonGroup();
		config = { ...baseConfig, ...config };
		callback &&
			callback(this.formInstance as BasicFormBox<Form>, {
				btn: this.buttonGroup,
			});
		Promise.resolve().then(() => {
			if (config?.isReset) {
				this.formInstance.reset();
			}
			if (config?.labelWidth) {
				this.formInstance.setLabelWidth(config?.labelWidth);
			}
			if (config?.isClear) {
				this.formInstance.clear();
			}
		});
		return this;
	}
	/**
	 * 初始化按钮
	 * @param callback 按钮的回调，可获取按钮组实例，进行按钮配置
	 * @returns
	 */
	initButton<Form = Record<string, any>>(
		callback: (btn: ButtonGroup, others?: { form: BasicFormBox<Form> }) => void
	) {
		callback &&
			callback(this.buttonGroup, {
				form: this.formInstance as BasicFormBox<Form>,
			});
		return this;
	}
	/**
	 * 打开弹出层
	 * @param opts 弹出层配置
	 * @returns
	 */
	open(opts: DialogOptions): Promise<PopupComponentEvent> {
		const res = this.showPopup(opts, false);
		this.formInstance = repaintProxy(
			this.formInstance,
			key => {
				return FORM_BOX_METHOD.includes(key);
			},
			() => {
				res.repaint();
			}
		);
		return new Promise(resolve => {
			const event: PopupComponentEvent = {
				getFormInstance: () => {
					return this.formInstance;
				},
				shutDown: res.shutDown,
			};
			resolve(event);
		});
	}
	/**
	 * 获取中间内容的VNode
	 * @returns
	 */
	getContentVNode(): VNode {
		return this.formInstance.getVNode();
	}
	/**
	 * 获取底部按钮组VNode
	 * @returnsgit
	 */
	getBottomVNode(): VNode {
		return this.buttonGroup.getVNode();
	}
	/**
	 * 获取表单实例
	 * @returns
	 */
	getFormInstance = () => {
		return this.formInstance;
	};
}

const dialog = new Dialog();

export { dialog };
